package com.easyshopping;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView.OnEditorActionListener;

import com.easyshopping.domain.Item;
import com.easyshopping.facade.ShoppingListFacade;


public class ShoppingListActivity extends Activity implements OnClickListener, OnCheckedChangeListener, OnEditorActionListener, OnFocusChangeListener {

	private ListView ls_shoppingList;
	private Button btn_addItem;
	private TextView tv_slName;
	private EditText et_slName;
	private Button btn_back;
	private Button btn_AllorRest;
	private Cursor cursor_item;
	
	private boolean mShowAll = true;
	
	private int itemPos = -2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.shopping_list);
		
		ls_shoppingList = (ListView)this.findViewById(R.id.ShoppingList);
		fillItems();
		
//	    ls_shoppingList.setAdapter(new ItemAdapter(this));
//		ls_shoppingList.setOnItemClickListener(this);
	     
	    btn_addItem = (Button)this.findViewById(R.id.AddItem);
	    btn_addItem.setOnClickListener(this);
	    
//	    Bundle extras = getIntent().getExtras();
//	    if (extras != null) {
//	    	this.setSlID(extras.getInt(SLID));
//	    	this.setSlName(extras.getString(SLNAME));
//	    }

	    tv_slName = (TextView)this.findViewById(R.id.SLName);
	    //
	    SpannableString content = new SpannableString(ShoppingListFacade.getInstance().getCurrentSL().getName());
	    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
	    tv_slName.setText(content);
	    //
//	    tv_slName.setText(ShoppingListFacade.getInstance().getCurrentSL().getName());
	    tv_slName.setOnClickListener(this);
	    
	    et_slName = (EditText)this.findViewById(R.id.ET_Shoppinglist_Name);
//	    et_slName.setOnKeyListener(this);
	    et_slName.setOnEditorActionListener(this);
	    et_slName.setOnFocusChangeListener(this);
	    et_slName.setVisibility(EditText.GONE);
	   
	    btn_back= (Button)this.findViewById(R.id.Back);
	    btn_back.setOnClickListener(this);
	    
	    btn_AllorRest = (Button)this.findViewById(R.id.Btn_AllorRestItems);
	    btn_AllorRest.setOnClickListener(this);
	}

	public void onClick(View view) {
		
		if (view.equals(btn_addItem)) {
			Intent intent = new Intent(this, AddItemActivity.class);
			this.startActivity(intent);
			return;
		} 
		if (view.equals(btn_back)) {
			this.finish();
			return;
		}
		if (view.equals(tv_slName)) {
			
			tv_slName.setVisibility(TextView.GONE);
			et_slName.setVisibility(EditText.VISIBLE);
			et_slName.setOnFocusChangeListener(this);
			et_slName.setText(ShoppingListFacade.getInstance().getCurrentSL().getName());
			et_slName.requestFocus();
//			et_slName.setImeOptions(EditorInfo.IME_ACTION_DONE);
//			et_slName.setOnKeyListener(this);

			return;
		}
		if (view.getId() == R.id.ListItem) {
			
//			this.setItemPos(-2);
//			cursor_item.requery();
			
			this.resetSLName();
			
//			Button btn_ItemEdit = (Button)view.findViewById(R.id.Btn_Item_Edit);
//			Button btn_ItemDelete = (Button)view.findViewById(R.id.Btn_Item_Delete);
//			Button btn_ItemMore = (Button)view.findViewById(R.id.Btn_Item_More);
//			
//			btn_ItemEdit.setVisibility(Button.GONE);
//			btn_ItemDelete.setVisibility(Button.GONE);
//			btn_ItemMore.setVisibility(Button.VISIBLE);
			
//			view.requestFocus();
			
			return;
		}
		Button btn = (Button)view;
		if (btn.getId() == R.id.Btn_Item_More) {
			
//			LinearLayout ll = (LinearLayout)btn.getParent();
//			Button btn_ItemEdit = (Button)ll.findViewById(R.id.Btn_Item_Edit);
//			Button btn_ItemDelete = (Button)ll.findViewById(R.id.Btn_Item_Delete);
//			Button btn_ItemMore = (Button)ll.findViewById(R.id.Btn_Item_More);
//			
//			btn_ItemMore.setVisibility(Button.GONE);
//			
//			btn_ItemEdit.setVisibility(Button.VISIBLE);
//			btn_ItemDelete.setVisibility(Button.VISIBLE);
//			btn_ItemEdit.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left));
//			btn_ItemDelete.startAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_left));
			
			this.setItemPos(((Integer)(btn.getTag())).intValue());
			cursor_item.requery();
			return;
		}
		if (btn.getId() == R.id.Btn_Item_Hide) {
			
			this.setItemPos(-2);
			cursor_item.requery();
			return;
		}
		if (btn.getId() == R.id.Btn_Item_Delete) {
			
			final int item_id = ((Integer)(btn.getTag())).intValue();
			
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.page_delete_question).setCancelable(false)
			.setPositiveButton(R.string.button_yes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   ShoppingListFacade.getInstance().deleteItem(item_id);
		        	   dialog.cancel();
		        	   cursor_item.requery();
		           }
		       }).setNegativeButton(R.string.button_no, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel();
		           }
		       });
			AlertDialog alert = builder.create();
			alert.show();
			return;
		}
		if (btn.getId() == R.id.Btn_Item_Edit) {
			
			final int item_id = ((Integer)(btn.getTag())).intValue();
			
			Intent intent = new Intent(this, ItemInfoActivity.class);
			intent.putExtra(Item.ITEM_ID, item_id);
			this.startActivity(intent);
			return;
		}
		
		if (btn.getId() == R.id.Btn_AllorRestItems) {
			
			mShowAll = !mShowAll;
			fillItems();
			
			if (mShowAll) {
				btn_AllorRest.setText(R.string.page_shoppingList_button_remainingList);
			} else {
				btn_AllorRest.setText(R.string.page_shoppingList_button_allList);
			}
			return;
		}
		
	}
	
	private void fillItems() {
		
		
		if (mShowAll) {
			cursor_item = ShoppingListFacade.getInstance().getPersistence().fetchAllItemsOfShoppingList(
					ShoppingListFacade.getInstance().getCurrentSL().getId());
		} else {
			cursor_item = ShoppingListFacade.getInstance().getPersistence().fetchRestItemsOfShoppingList(
					ShoppingListFacade.getInstance().getCurrentSL().getId());
		}
		
//		cursor_item = ShoppingListFacade.getInstance().getPersistence().fetchAllItemsOfShoppingList(
//				ShoppingListFacade.getInstance().getCurrentSL().getId());
		
        startManagingCursor(cursor_item);

//        String[] from = new String[] { Item.ITEM_NAME, Item.ITEM_STATE };
//        int[] to = new int[] { R.id.Item, R.id.CheckBox01 };
//        
//        // Now create an array adapter and set it to display using our row
//        SimpleCursorAdapter sls =
//            new SimpleCursorAdapter(this, R.layout.list_item, c, from, to);
//        sls.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
//            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
//                if(cursor.getColumnName(columnIndex).equals(Item.ITEM_STATE)) {
//                        CheckBox cb = (CheckBox) view;
//                        cb.setChecked(cursor.getInt(columnIndex) != 0);
//                        return true;
//                }
//                return false;
//            }
//        });
//
//        ls_shoppingList.setAdapter(sls);
        
        ls_shoppingList.setAdapter(new ItemCursorAdapter(this, cursor_item));
	}
	
	
	
	private class ItemCursorAdapter extends ResourceCursorAdapter {
		
		public ItemCursorAdapter(Context context, Cursor cur) {
			super(context, R.layout.list_item, cur);
		}
		
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			
			LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			return inflator.inflate(R.layout.list_item, parent, false);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			
			TextView tv_Item = (TextView)view.findViewById(R.id.Item);
			tv_Item.setText(cursor.getString(cursor.getColumnIndex(Item.ITEM_NAME)));
			
			CheckBox cb_state = (CheckBox)view.findViewById(R.id.CheckBox01);
			int item_id = cursor.getInt(cursor.getColumnIndex(Item.ITEM_ID));
			cb_state.setTag(new Integer(item_id));
			cb_state.setOnCheckedChangeListener(ShoppingListActivity.this);
			cb_state.setChecked(cursor.getInt(cursor.getColumnIndex(Item.ITEM_STATE)) != 0);
			
			Button btn_ItemHide = (Button)view.findViewById(R.id.Btn_Item_Hide);
			btn_ItemHide.setTag(new Integer(item_id));
			btn_ItemHide.setOnClickListener(ShoppingListActivity.this);
			
			Button btn_ItemEdit = (Button)view.findViewById(R.id.Btn_Item_Edit);
			btn_ItemEdit.setTag(new Integer(item_id));
//			btn_ItemEdit.setVisibility(Button.GONE);
			btn_ItemEdit.setOnClickListener(ShoppingListActivity.this);
			
			Button btn_ItemDelete = (Button)view.findViewById(R.id.Btn_Item_Delete);
			btn_ItemDelete.setTag(new Integer(item_id));
//			btn_ItemDelete.setVisibility(Button.GONE);
			btn_ItemDelete.setOnClickListener(ShoppingListActivity.this);
			
			Button btn_ItemMore = (Button)view.findViewById(R.id.Btn_Item_More);
			btn_ItemMore.setTag(new Integer(item_id));
			btn_ItemMore.setOnClickListener(ShoppingListActivity.this);
//			btn_ItemMore.setVisibility(Button.VISIBLE);

			if (item_id == ShoppingListActivity.this.getItemPos()) {
				btn_ItemMore.setVisibility(Button.GONE);
				
				btn_ItemEdit.setVisibility(Button.VISIBLE);
				btn_ItemDelete.setVisibility(Button.VISIBLE);
				btn_ItemHide.setVisibility(Button.VISIBLE);
				btn_ItemHide.startAnimation(AnimationUtils.loadAnimation(ShoppingListActivity.this, R.anim.slide_left));
				btn_ItemEdit.startAnimation(AnimationUtils.loadAnimation(ShoppingListActivity.this, R.anim.slide_left));
				btn_ItemDelete.startAnimation(AnimationUtils.loadAnimation(ShoppingListActivity.this, R.anim.slide_left));
				
			} else {
				
				btn_ItemEdit.setVisibility(Button.GONE);
				btn_ItemDelete.setVisibility(Button.GONE);
				btn_ItemHide.setVisibility(Button.GONE);
				btn_ItemMore.setVisibility(Button.VISIBLE);
			}
			
			view.setOnClickListener(ShoppingListActivity.this);
		}
		
	}
	
//	private class ItemAdapter extends BaseAdapter {
//
//		private String[] mStrings = {
//	            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
//	            "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
//	            "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
//	            "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh"};
//		
//		private Context mContext;
//		
//		public ItemAdapter(Context context) {
//			this.mContext = context;
//		}
//		
//		public int getCount() {
//			return mStrings.length;
//		}
//
//		public Object getItem(int position) {
//			return position;
//		}
//
//		public long getItemId(int position) {
//			return position;
//		}
//
//		public View getView(int position, View convertView, ViewGroup parent) {
//			
//			ListItemView view;
//			
//			if (convertView == null) {
//				view = new ListItemView(mContext);
//			} else {
//				view = (ListItemView)convertView;
//			}
//			
//			view.setItem(mStrings[position]);
//			
//			return view;
//		}
//		
//	}
//	
//	 private class ListItemView extends LinearLayout {
//
//		private TextView tv_item;
//		 
//		public ListItemView(Context context) {
//			super(context);
//			
//			LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//			View view = inflator.inflate(R.layout.list_item, this);
//			
//			tv_item = (TextView)view.findViewById(R.id.Item);
//		}
//		 
//		public void setItem(String item) {
//			tv_item.setText(item);
//		}
//		
//	 }

//	public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//		
//		Intent intent = new Intent(this, AddItemActivity.class);
//		this.startActivity(intent);
//	}

	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		
		int item_id = ((Integer)buttonView.getTag()).intValue();
		ShoppingListFacade.getInstance().updateItemState(item_id, isChecked);
		
//		this.setItemPos(-2);
		buttonView.setChecked(isChecked);
		cursor_item.requery();
	}

//	public boolean onKey(View v, int keyCode, KeyEvent event) {
//		
//		if ((event.getAction() == KeyEvent.ACTION_DOWN)
//				&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
//			
//			ShoppingListFacade.getInstance().getCurrentSL().setName(et_slName.getText().toString());
//			ShoppingListFacade.getInstance().updateShoppinglist(ShoppingListFacade.getInstance().getCurrentSL());
//			
//			tv_slName.setVisibility(TextView.VISIBLE);
//			et_slName.setVisibility(EditText.GONE);
//			tv_slName.setText(ShoppingListFacade.getInstance().getCurrentSL().getName());
//			return true;
//		}
//
//		return false;
//	}

	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		
		if (actionId == EditorInfo.IME_ACTION_DONE || actionId == KeyEvent.ACTION_DOWN) {
			
			if (et_slName.getText().toString().trim().length() != 0) {
				ShoppingListFacade.getInstance().getCurrentSL().setName(et_slName.getText().toString().trim());
				ShoppingListFacade.getInstance().updateShoppinglist(ShoppingListFacade.getInstance().getCurrentSL());
			}
				
			resetSLName();
			
		}
		return false;
	}

	public void onFocusChange(View v, boolean hasFocus) {
		
		if (!hasFocus) {
			resetSLName();
		} else {
			this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		}
	}

	private void resetSLName() {
		tv_slName.setVisibility(TextView.VISIBLE);
		et_slName.setVisibility(EditText.GONE);
//		tv_slName.setText(ShoppingListFacade.getInstance().getCurrentSL().getName());
		SpannableString content = new SpannableString(ShoppingListFacade.getInstance().getCurrentSL().getName());
	    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
	    tv_slName.setText(content);
	}

	public int getItemPos() {
		return itemPos;
	}

	public void setItemPos(int itemPos) {
		this.itemPos = itemPos;
	}

}
